/*================================================================
*   Copyright (C) 2024 baichao All rights reserved.
*
*   文件名称：main.c
*   创 建 者：baichao
*   创建日期：2024年04月13日
*   描
述：首先初始化一个足够大的结果链表ret，然后遍历两个输入链表并对每一位执行加法操作，同时处理进位。
             最后，如果存在最高位的进位，会在结果链表末尾添加一个新的节点存储进位值。
*
================================================================*/

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

struct ListNode {
  int val;
  struct ListNode *next;
};

struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2) {
  struct ListNode *ret =
      (struct ListNode *)calloc(101, sizeof(struct ListNode));
  int currDigit = 0;  // 当前位的值
  int carry = 0;      // 表示进位
  int index = 0;
  while (!(l1 == NULL && l2 == NULL)) {
    if (l1 != NULL) {
      currDigit += l1->val;
      l1 = l1->next;
    }
    if (l2 != NULL) {
      currDigit += l2->val;
      l2 = l2->next;
    }
    currDigit += carry;

    if (currDigit > 9) {
      currDigit -= 10;
      carry = 1;
    } else {
      carry = 0;
    }

    ret[index].val = currDigit;
    if (index >= 1) {
      ret[index - 1].next = ret + index;
    }
    currDigit = 0;
    index++;
  }

  if (index >= 1 && carry == 1) {
    ret[index].val = carry;
    ret[index - 1].next = ret + index;
    index++;
  }
  ret[index].next = NULL;
  return ret;
}

int main() {
  struct ListNode *currNode = NULL;
  struct ListNode *listA = (struct ListNode *)malloc(sizeof(struct ListNode));

  listA->val = 9;
  listA->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = listA->next;

  currNode->val = 9;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 9;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 9;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 9;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 9;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 9;
  currNode->next = NULL;

  currNode = NULL;
  struct ListNode *listB = (struct ListNode *)malloc(sizeof(struct ListNode));

  listB->val = 9;
  listB->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = listB->next;

  currNode->val = 9;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 9;
  currNode->next = (struct ListNode *)malloc(sizeof(struct ListNode));
  currNode = currNode->next;

  currNode->val = 9;
  currNode->next = NULL;

  addTwoNumbers(listA, listB);
}
